package com.aduerr.v1shouyin.mvp.activity;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.common.DatabaseManager;
import com.aduerr.v1shouyin.entity.OrderRecordEntity;
import com.aduerr.v1shouyin.entity.UpdateUnionPayOrderStateEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.unioncard.UnionTranscationRecordActivity;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.orhanobut.hawk.Hawk;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;


/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2018/10/18 9:40
 * @change
 * @chang time
 * @class describe
 */

public class RefundActivity extends AppCompatActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refund);
        ButterKnife.bind(this);
        tvTitle.setText("交易退款");
    }

    @OnClick({R.id.img_back, R.id.ll_bank, R.id.ll_scan, R.id.ll_record})
    void clicked(View v) {
        switch(v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.ll_bank:
//                toXingPos();
                if(Hawk.get(Constants.IS_ACTIVE, false)) {
                    startActivity(new Intent(RefundActivity.this,
                            UnionTranscationRecordActivity.class));
                } else {
                    ToastUtils.showToast(this, "银联功能未激活，请联系运营");
                }
                break;
            case R.id.ll_scan:
                Intent intent3 = new Intent(RefundActivity.this, ScanningActivity.class);
                intent3.putExtra(Constants.QRCODE_CAPUTER, Constants.REFUND_QR);
                startActivity(intent3);
                break;
            case R.id.ll_record:
                startActivity(new Intent(RefundActivity.this,
                        RefundRecordActivity.class));
                break;
        }
    }

    private void toXingPos() {
        //YYYYMMDDhhmmss
        try {
            String stringDate = getStringDate();
            ComponentName component = new ComponentName("com.newland.caishen", "com" +
                    ".newland.caishen.ui.activity.MainActivity");
            Intent intent = new Intent();
            intent.setComponent(component);

            Bundle bundle = new Bundle();
            bundle.putString("msg_tp", "0200");//0300 查询   0200 消费和撤销
            bundle.putString("pay_tp", "0");
            bundle.putString("proc_tp", "00");
            bundle.putString("proc_cd", "200000");//撤销
//            bundle.putString("proc_cd", "000000");//消费
//            bundle.putString("amt", "0.01");
//            bundle.putString("order_no", "100012345678932101");
            bundle.putString("appid", "com.aduer.v1shouyin");
            bundle.putString("time_stamp", stringDate);
//            bundle.putString("print_info", "订单商品明细单价等xxxxxx");
            intent.putExtras(bundle);
            this.startActivityForResult(intent, 1);
        } catch(ActivityNotFoundException e) {
            //TODO:
        } catch(Exception e) {
            //TODO:
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("银联问题排查","更新银联订单");
        //xingpos
        if(data == null) return;
        Bundle bundle = data.getExtras();
        if(requestCode == 1 && bundle != null) {
            switch(resultCode) {
                // 支付成功
                case Activity.RESULT_OK:
                    String msgTp = bundle.getString("msg_tp");
                    String proc_cd = bundle.getString("proc_cd");
                    if(TextUtils.equals(msgTp, "0210")) {
                        try {
                            Toast.makeText(RefundActivity.this, "退款成功",
                                    Toast.LENGTH_SHORT).show();
                            String txndetail = bundle.getString("txndetail");
                            JSONObject jsonObject = new JSONObject(txndetail);
                            OrderRecordEntity order = new OrderRecordEntity();
                            order.setType(12);
                            order.setMerchantName(jsonObject.optString("mername"));
                            order.setTermId(jsonObject.optString("termid"));
                            order.setBankAccount(jsonObject.optString("priaccount"));
                            order.setBankCode(jsonObject.optString("acqno"));
                            order.setBankName(jsonObject.optString("iisno"));
                            order.setBatchNo(jsonObject.optString("batchno"));
                            order.setSysTraceNo(jsonObject.optString("systraceno"));
                            order.setReferNo(jsonObject.optString("refernumber"));
                            order.setExpDate(jsonObject.optString("expdate"));
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd " +
                                    "HH:mm:ss");
                            Date time = null;
                            try {
                                time = sdf.parse(jsonObject.optString("translocaldate") + jsonObject.optString("translocaltime"));
                                order.setPayTime(sdf2.format(time));
                            } catch(ParseException e) {
                                e.printStackTrace();
                            }
                            String systraceno = jsonObject.optString("termid") + jsonObject.optString("translocaldate") + bundle.getString("sysoldtraceno");
                            if(proc_cd.equals("200000")) {
                                payShouKuan(systraceno, "-2",order.getOrderMoney());
                            }
                            order.setOrderMoney(jsonObject.optString("transamount"));
                            DatabaseManager.getInstance().insert(order);
                        } catch(JSONException e) {
                            e.printStackTrace();
                        }

                    }
                    break;
                // 支付取消
                case Activity.RESULT_CANCELED:
                    String reason = bundle.getString("reason");
                    if(reason != null) {
                        // TODO:
                        Toast.makeText(RefundActivity.this, "退款取消", Toast.LENGTH_SHORT).show();
                        //                        finish();
                    }
                    break;
            }
        }

    }

    /**
     * 获取现在时间
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }


    private void payShouKuan(String outOrderID,String orderState,String refundAmount ) {
        Log.i("银联问题排查","更新银联订单");
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("OutOrderID", outOrderID);
        addParams.put("OrderState", orderState);
        if(!TextUtils.isEmpty(refundAmount)){
            addParams.put("RefundAmount", refundAmount);
        }
        APIRetrofit.getAPIService().UpdateUnionPayOrderState(RXRequest.getXingPosParams(addParams, RefundActivity.this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UpdateUnionPayOrderStateEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull UpdateUnionPayOrderStateEntity unionPayOrderStateEntity) {
                        int success = unionPayOrderStateEntity.getSuccess();
                        if(success == 1) {

                            ToastUtils.showToast(RefundActivity.this,
                                    unionPayOrderStateEntity.getErrMsg() + "");
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            startActivity(new Intent(RefundActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(unionPayOrderStateEntity.getErrMsg());
                            SharedPreferencesUtils.remove(RefundActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(RefundActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(RefundActivity.this,
                                    LoginActivity.class));
                            finish();
                        } else {
                            ToastUtils.showToast(RefundActivity.this,
                                    unionPayOrderStateEntity.getErrMsg() + "");
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
